/**
Author  tudo
一个测试api 接口的工具
支持的 请求  http
支持的数据 格式 json

*/

package main

import (
	"fmt"
	"io/ioutil"
	"net/url"
	"html/template"
	"log"
	"net/http"
)

type Config struct {
	MyApi     string
	MyHost    string
	MyPort    string
	MyTitle   string
	MyVersion string
}

var config Config
var data map[string]interface{}

func init() {
	config.MyApi = "http://mobileapi.nethealth.cn/mobile/"
	config.MyHost = "http://localhost"
	config.MyPort = "7070"
	config.MyTitle = "接口调试盒子-名医生"
	config.MyVersion = "1.0"
	data = make(map[string]interface{})
	data["myApi"] = config.MyApi
	data["myUrl"] = config.MyHost + ":" + config.MyPort
	data["version"] = config.MyVersion
	data["title"] = config.MyTitle
}
func main() {
	Run()
}

func Run() {
	fmt.Printf("正在监听：%s\n", config.MyPort)
	http.HandleFunc("/", IndexHandler)
	//set static path
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
	err := http.ListenAndServe(":" + config.MyPort, nil)
	if err != nil {
		log.Fatal(err)
	}
	//打印消息


}

func IndexHandler(r http.ResponseWriter, rq *http.Request) {
	if rq.Method == "POST" {
		//获取参数
		Post(r, rq)
	} else {
		Get(r, rq)
	}
}

func Post(w http.ResponseWriter, r *http.Request) {
	//设置内存
	r.ParseForm()
	urls := r.FormValue("url")
	method := r.FormValue("method")
	if urls == "" || method == "" {
		data := `{"code":"error","msg":"没有传参数"}`
		w.Write([]byte(data))
		return
	}

	delete(r.Form, "url")
	delete(r.Form, "method")
	var err error
	var resp *http.Response
	if method == "get" {
		u, _ := url.Parse(urls)
		q := u.Query()
		for k, v := range r.Form {
			q.Set(k, v[0])
		}
		u.RawQuery = q.Encode()
		resp, err = http.Get(u.String())
	} else {
		resp, err = http.PostForm(urls, r.Form)
	}
	if err != nil {
		log.Fatal("服务端发送请求失败")
	}
	if resp.StatusCode != 200 {
		data := fmt.Sprintf(`{"code":"%d"}`, resp.StatusCode)
		w.Write([]byte(data))
		return
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	w.Write(body)
}

func Get(r http.ResponseWriter, req *http.Request) {
	t, err := template.ParseFiles("view/index.html")
	if err != nil {
		log.Panic("模板解析失败")
	}
	err = t.Execute(r, data)
	if err != nil {
		log.Panic("模板执行失败")
	}

}
